package linker.file;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import linker.window.WindowSaver;

import org.jivesoftware.smackx.filetransfer.FileTransferRequest;
import org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer;

/**
 * THe File manager
 * 
 * @version linker 0.93
 * @author Jianfeng coxzjkwl@gmail.com
 * 
 */
public class FileManager extends JFrame implements ActionListener {
	// @_@
	private static final long serialVersionUID = 1L;

	// The file manager object refer to itself
	private static FileManager fileManager = null;

	// The table to display the file list
	private JTable table = new JTable();

	private JButton acceptButton = new JButton("Accept");

	private JButton refreshButton = new JButton("Refresh");

	private JButton cancelButton = new JButton("Cancel");

	private static FileTableModel fileTableModel = new FileTableModel();

	private FileManager() {
		super("File mananger");

		Container container = getContentPane();
		container.setLayout(new BorderLayout());

		JPanel userPanel = new JPanel();
		refreshButton.addActionListener(this);
		userPanel.add(refreshButton);
		acceptButton.addActionListener(this);
		userPanel.add(acceptButton);
		cancelButton.addActionListener(this);
		userPanel.add(cancelButton);
		container.add(userPanel, BorderLayout.NORTH);

		table.setColumnSelectionAllowed(false);
		table.setCellSelectionEnabled(false);
		table.setRowSelectionAllowed(true);

		table.setModel(fileTableModel);
		container.add(new JScrollPane(table), BorderLayout.CENTER);

		setSize(400, 400);
		setLocationRelativeTo(null);
		try {
			WindowSaver.getWindowSaver().loadSettings(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
		setVisible(false);
	}

	public static FileManager getFileManager() {
		if (fileManager == null)
			fileManager = new FileManager();

		return fileManager;
	}

	public static void addRecieveFile(FileTransferRequest request) {
		getFileManager();

		fileTableModel.addRecieveFile(request);
	}

	public static void addSendFile(OutgoingFileTransfer sendFileRequest) {
		getFileManager();

		fileTableModel.addSendFile(sendFileRequest);
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == cancelButton)
			fileTableModel.cancel(table.getSelectedRow());
		else if (e.getSource() == acceptButton)
			fileTableModel.accept(table.getSelectedRow());
		else if (e.getSource() == refreshButton)
			fileTableModel.refresh();

	}

}
